package com.pactera.bledemo.activity.traditional

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.dylanc.viewbinding.nonreflection.binding
import com.pactera.bledemo.base.BaseActivity
import com.pactera.bledemo.databinding.ActivityBaseBlueToothBinding

class BaseBlueToothActivity : BaseActivity() {
    private val binding by binding(ActivityBaseBlueToothBinding::inflate)//不使用反射
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        registerBleReceiver()
        initListener()
    }

    private fun registerBleReceiver() {
        val filter = IntentFilter()
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        filter.addAction(BluetoothDevice.ACTION_FOUND)
        registerReceiver(receiver, filter)
    }

    private fun initListener() {
        binding.apply {
            openButton1.setOnClickListener {
                //方法一:隐式打开，回有弹出提示框
                //隐式打开，回有弹出提示框
                val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(intent, 1)
            }
            openButton2.setOnClickListener {
                //方法二：静默打开
                println("BaseBlueToothActivity.initListener mBluetoothAdapter?.isEnabled=${mBluetoothAdapter?.isEnabled}")
                if (mBluetoothAdapter?.isEnabled == false) {
                    //若没打开则打开蓝牙
                    mBluetoothAdapter?.enable();
                }
            }
            closeButton.setOnClickListener {
                println("BaseBlueToothActivity.initListener closeButton .isEnabled=${mBluetoothAdapter?.isEnabled}")
                if (mBluetoothAdapter?.isEnabled() == true) {
                    //若没打开则打开蓝牙
                    mBluetoothAdapter?.disable()
                }
            }

            scanButton.setOnClickListener {
                if (mBluetoothAdapter?.isDiscovering() == true) { //如果当前在搜索，就先取消搜索
                    mBluetoothAdapter?.cancelDiscovery()
                }
                mBluetoothAdapter?.startDiscovery() //开启搜索
            }
            addressButton.setOnClickListener {
                val blueToothAddress = getBlueToothAddress()
                binding.tv.text = blueToothAddress
            }


            alreadyPairedBtn.setOnClickListener {
                val str = getPairedDevices()
                binding.tv.setText(str)
            }
        }
    }


    /**
     * 定义广播接收器
     */
    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.i(TAG, "onReceive: action=$action")
            if (action == BluetoothAdapter.ACTION_DISCOVERY_STARTED) {
                Log.i(TAG, "onReceive:  扫描开始")
            } else if (action == BluetoothAdapter.ACTION_DISCOVERY_FINISHED) {
                Log.i(TAG, "onReceive:  扫描完成")
            } else if (action == BluetoothDevice.ACTION_FOUND) {
                Log.i(TAG, "onReceive:  发现周围设备广播")
                val bluetoothDevice =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                val name = bluetoothDevice!!.name
                val address = bluetoothDevice.address
                Log.i(TAG, "onReceive:  name=$name address=$address")
                binding.tv.append("name=$name address=$address \n")
                //bluetoothDevices.add("$name:$address")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "onActivityResult: 请求码=$requestCode 结果码=$resultCode")
        when (resultCode) {
            RESULT_OK -> {
                Log.i(TAG, "onActivityResult: 蓝牙已打开")
                Toast.makeText(this@BaseBlueToothActivity, "蓝牙已打开", Toast.LENGTH_SHORT).show();
            }
            RESULT_CANCELED -> {
                Log.i(TAG, "onActivityResult: 打开请求被拒绝")
                Toast.makeText(this@BaseBlueToothActivity, "打开请求被拒绝", Toast.LENGTH_SHORT).show();
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
        mBluetoothAdapter?.cancelDiscovery()
    }

    /**
     * 返回本地蓝牙适配器的硬件地址
     */
    private fun getBlueToothAddress(): String? {
        return mBluetoothAdapter?.getAddress()
    }

    /**
     * 获取已经配对的蓝牙设备
     */
    fun getPairedDevices(): String? {
        val sb = StringBuffer()
        val pairedDevices: Set<BluetoothDevice> = mBluetoothAdapter?.getBondedDevices()!!
        if (pairedDevices.size > 0) {
            for (device in pairedDevices) {
                sb.append("已经配对：" + device.name + ":" + device.address + " ")
            }
        }
        return sb.toString()
    }


    /**
     * 验证蓝牙 地址的格式 是否正确
     */
    fun isRightBluetoothAddress(address: String?): Boolean {
        return BluetoothAdapter.checkBluetoothAddress(address)
    }

}